package com.example.zhunongzonghe.service.impl;

import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.zhunongzonghe.beans.ZnCollectHouseBean;
import com.example.zhunongzonghe.beans.ZnFarmhouseBean;
import com.example.zhunongzonghe.dao.ZnCollectHouseMapper;
import com.example.zhunongzonghe.dao.ZnFarmhouseMapper;
import com.example.zhunongzonghe.entity.ZnCollectFarm;
import com.example.zhunongzonghe.entity.ZnCollectHouse;
import com.example.zhunongzonghe.entity.ZnFarmhouse;
import com.example.zhunongzonghe.entity.ZnUsers;
import com.example.zhunongzonghe.enums.FarmCollectStatusEnum;
import com.example.zhunongzonghe.service.IZnUsersService;
import com.example.zhunongzonghe.service.ZnCollectHouseService;
import com.example.zhunongzonghe.utils.RedisCache;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;

/**
* @author 蔡某人
* @description 针对表【zn_collect_house】的数据库操作Service实现
* @createDate 2024-04-09 23:57:01
*/
@Service
public class ZnCollectHouseServiceImpl extends ServiceImpl<ZnCollectHouseMapper, ZnCollectHouse>
    implements ZnCollectHouseService{


    @Resource
    private RedisCache redisCache;
    @Resource
    private IZnUsersService znUsersService;
    @Resource
    private ZnCollectHouseMapper znCollectHouseMapper;
    @Resource
    private ZnFarmhouseMapper znFarmhouseMapper;

    private static final String HOUSE_COLLECT_KEY = "house_collect";//hash前缀
    private static final String HOUSE_COLLECT_COUNT_KEY = "house_collect_count";//收藏总数前缀
    private static final String HOUSE_COLLECT_DETAIL_KEY = "house_collect_detail";//收藏状态

    @Override
    public void addCollect(ZnCollectHouseBean znCollectHouseBean, String userName) {
        ZnUsers znUsers = znUsersService.getUserName(userName);
        Integer houseId = znCollectHouseBean.getHouseId();
        Integer userId = znUsers.getId();
        Integer status = znCollectHouseBean.getCollectStatus();
        //与redis做交互的Hash的key
        String collectHashKey = collectHashKey(houseId.toString(),userId.toString());
        redisCache.setCacheHashValue(HOUSE_COLLECT_KEY,collectHashKey,status);
        String detailKey = HOUSE_COLLECT_DETAIL_KEY+"."+houseId+"."+userId;//被谁点过赞的key
        String countKey = HOUSE_COLLECT_COUNT_KEY+"."+houseId;
        if (FarmCollectStatusEnum.COLLECT.getCode() == status){
            redisCache.increment(countKey,1);//收藏时加1
            redisCache.setCacheObject(detailKey,"1");
        }else {
            Integer count =redisCache.getInt(countKey);
            if (Objects.isNull(count) || count<0){
                return;
            }
            redisCache.increment(countKey,-1);//取消收藏时-1
            redisCache.deleteObject(detailKey);
        }
    }

    @Override
    public Boolean isCollect(Integer farmId, Integer userId) {
        String detailKey = HOUSE_COLLECT_DETAIL_KEY+"."+farmId+"."+userId;//被谁点过收藏的key
        return redisCache.exist(detailKey);//获取redis内的detailKey，如果存在说明当前用户收藏过该帖子
    }

    @Override
    public Integer CollectCounts(Integer farmId) {
        String countKey = HOUSE_COLLECT_COUNT_KEY+"."+farmId;
        Integer count =redisCache.getInt(countKey);
        if (Objects.isNull(count) || count<0){
            return 0;
        }
        return redisCache.getInt(countKey);
    }

    @Override
    public void syncFarmCollect() {
        Map<Object,Object> farmCollectMap = redisCache.getHashAndDelete(HOUSE_COLLECT_KEY);
        if (MapUtil.isEmpty(farmCollectMap)){
            return;
        }
        //批量同步到数据库
        List<ZnCollectFarm> znCollectFarms = new ArrayList<>();
        farmCollectMap.forEach((key,value) ->{
            ZnCollectFarm znCollectFarm = new ZnCollectFarm();
            String[] keyArr = key.toString().split(":");
            String postId = keyArr[0];
            String UserId = keyArr[1];
            znCollectFarm.setFarmId(Integer.valueOf(postId));
            znCollectFarm.setUserId(Integer.valueOf(UserId));
            znCollectFarm.setCollectStatus((Integer) value);
            znCollectFarm.setCreateTime(LocalDateTime.now());
            znCollectFarm.setUpdateTime(LocalDateTime.now());
            znCollectFarms.add(znCollectFarm);
        });
        znCollectHouseMapper.insertList(znCollectFarms);
    }

    @Override
    public void delRepetition() {

    }

    @Override
    public Page<ZnFarmhouseBean> MyCollects(String username, Integer currentPage, Integer pageSize) {
        ZnUsers znUsers = znUsersService.getUserName(username);
        String key = HOUSE_COLLECT_KEY+"*"+znUsers.getId();
        Collection<String> keys = redisCache.keys(key);
        if (keys==null) return null;
        List<ZnFarmhouseBean> beanList = new ArrayList<>();
        for (String stringKey: keys
        ) {
            String[] parts = stringKey.split("\\."); // 使用 "." 分割字符串
            String houseId = parts[1]; // 第二部分即为 "21"
            Page<ZnFarmhouse> page = new Page<>(currentPage,pageSize);
            LambdaQueryWrapper<ZnFarmhouse> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ZnFarmhouse::getHouseId,houseId);
            Page<ZnFarmhouse> housePage = znFarmhouseMapper.selectPage(page,queryWrapper);
            for (ZnFarmhouse house: housePage.getRecords()
            ) {
                ZnFarmhouseBean houseBean = new ZnFarmhouseBean();
                houseBean.setCollectOrNot(isCollect(house.getHouseId(),znUsers.getId()));
                houseBean.setCollectCount(CollectCounts(house.getHouseId()));
                BeanUtils.copyProperties(house,houseBean);
                beanList.add(houseBean);
            }
        }
        Page<ZnFarmhouseBean> resultPage = new Page<>();
        resultPage.setRecords(beanList);
        resultPage.setSize(beanList.size());
        resultPage.setTotal(beanList.size());
        resultPage.setCurrent(currentPage);
        return resultPage;
    }

    private String collectHashKey(String farmId,String userId){
        return farmId + ":" +userId;
    }
}




